#!/bin/bash

input_file="$output_dir/$yosys_output_dot_filename_main.dot"
if ! [[ -f "$input_file" ]]; then
    echo "Error: File $input_file not found!" >&2
    exit 1
fi

depth=0
prev_depth=0
content=""
label_content=""
wait_ch="l"

while IFS= read -r -n1 ch; do
    prev_depth=$depth
    if [[ "$ch" == "{" ]]; then
        ((depth++))
    elif [[ "$ch" == "}" ]]; then
        ((depth--))
    fi
    content=$content""$ch

    if [ $depth -eq 1 ]; then
        if [ "$wait_ch" = "l" ] || [ "$wait_ch" = "a" ] || [ "$wait_ch" = "b" ] || [ "$wait_ch" = "e" ]; then
            if [ "$wait_ch" != "$ch" ]; then
                wait_ch="l"
            elif [ "$wait_ch" = "l" ]; then
                wait_ch="a"
            elif [ "$wait_ch" = "a" ]; then
                wait_ch="b"
            elif [ "$wait_ch" = "b" ]; then
                wait_ch="e"
            elif [ "$wait_ch" = "e" ]; then
                wait_ch="="
            fi
        elif [ "$wait_ch" = "=" ]; then
            if [ "$ch" = "=" ]; then
                wait_ch="L"
            fi
        elif [ "$wait_ch" = "L" ]; then
            if [ "$ch" = "\"" ]; then
                wait_ch="R"
            fi
        elif [ "$wait_ch" = "R" ]; then
            if [ "$ch" = "\"" ]; then
                wait_ch="*"
            else
                label_content=$label_content""$ch
            fi
        fi
    fi

    if [ $prev_depth -ne 0 ] && [ $depth -eq 0 ]; then
        out_path=$output_dir"/"$circuit_output_dirname"/"$label_content".dot"
        echo "$content" > "$out_path"
        content=""
        label_content=""
        wait_ch="l"
    fi
done < $input_file
